package cn.kawa.basic.controller;

import cn.kawa.basic.util.FastDfsUtils;
import cn.kawa.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping
    //RequestPart 用于处理复杂表单项
    public JsonResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            //获取文件名称
            String originalFilename = file.getOriginalFilename();//111.jpg
            //获取文件后缀，不要点
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //调用upload方法，并返回路径
            String uploadPath = FastDfsUtils.upload(file.getBytes(), suffix);
            //调用 setResultObj 方法，利用JsonResult传参uploadPath
            return JsonResult.me().setResultObj(uploadPath);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("上传失败");//
        }
    }

    @DeleteMapping
    //RequestParam 用于接收键值对参数
    //错误1：注意此处value="path"
    public JsonResult delete(@RequestParam(value = "path",required = true) String path){
        try {//  原始path值：/group1/M00/00/E5/CgAIC2Lc__uAGrPlAAIA-sRnCjo178.jpg
            System.out.println("测试path值："+path);
            String pathRow = path.substring(1);
            //通过pathRow调方法获取 group1 , 注意此时要传两个参数
            String group = pathRow.substring(0,pathRow.indexOf("/"));
            //其实就是根据 / 符号，将pathRow 分为两部分，才能调方法
            String lastPath = pathRow.substring(pathRow.indexOf("/") + 1);
            FastDfsUtils.delete(group,lastPath);
            return JsonResult.me();//此处只需返回成功即可，不需要携带参数
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");//
        }

    }



}
